<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form class="-mb-15px" :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
      <el-form-item label="等级" prop="levelId">
        <el-input v-model="queryParams.levelId" placeholder="请输入等级" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>
      <el-form-item label="状态" prop="writeStatus">
        <el-select v-model="queryParams.writeStatus" placeholder="请选择状态" clearable class="!w-240px">
          <el-option v-for="dict in getIntDictOptions(DICT_TYPE.WRITE_STATUS)" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="区域名称" prop="areaName">
        <el-input v-model="queryParams.areaName" placeholder="请输入区域名称" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px" /> 搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px" /> 重置
        </el-button>
        <!-- <el-button type="primary" plain @click="openForm('create')" v-hasPermi="['business:audit-plan-area:create']">
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button> -->
        <el-button type="success" plain @click="handleExport" :loading="exportLoading"
          v-hasPermi="['business:audit-plan-area:export']">
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
        <!-- <el-button type="danger" plain :disabled="isEmpty(checkedIds)" @click="handleDeleteBatch"
          v-hasPermi="['business:audit-plan-area:delete']">
          <Icon icon="ep:delete" class="mr-5px" /> 批量删除
        </el-button> -->
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table border row-key="id" v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true"
      @selection-change="handleRowCheckboxChange">
      <el-table-column type="selection" width="55" />
      <el-table-column label="等级" align="center" prop="levelName" />
      <el-table-column label="区域" align="center" prop="areaName" width="100" />
      <el-table-column label="所属范围" align="center" prop="belongType" width="100">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.BELONG" :value="scope.row.belongType" />
        </template>
      </el-table-column>
      <el-table-column label="审核日期" align="center" prop="auditStartDate" width="150" />
      <el-table-column label="审核人" align="center" prop="auditUserName" />
      <el-table-column label="状态" align="center" prop="writeStatus" width="100">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.WRITE_STATUS" :value="scope.row.writeStatus" />
        </template>
      </el-table-column>
      <el-table-column label="填报人" align="center" prop="writeUserName" />
      <el-table-column label="填报时间" align="center" prop="writeTime" :formatter="dateFormatter" width="180px" />
      <el-table-column label="下发人" align="center" prop="sendUserName" width="100" />
      <el-table-column label="下发时间" align="center" prop="sendTime" :formatter="dateFormatter" width="180px" />
      <el-table-column label="操作" align="center" min-width="220px" fixed="right">
        <template #default="scope">
          <el-button :disabled="!(scope.row.writeStatus == 1)" link type="primary"
            @click="openForm('update', scope.row.id)" v-hasPermi="['business:audit-plan-area:update']">
            填报
          </el-button>

          <el-button link type="primary" @click="openForm('view', scope.row.id)"
            v-hasPermi="['business:audit-plan-area:update']">
            查看
          </el-button>

          <el-button @click="showPrintPreview(scope.row)" type="success">打印</el-button>

        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination :total="total" v-model:page="queryParams.pageNo" v-model:limit="queryParams.pageSize"
      @pagination="getList" />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <AuditPlanAreaForm ref="formRef" @success="getList" />


  <!-- 打印预览对话框 -->

  <el-dialog width="80%" v-model="printPreviewVisible" title="打印预览" :close-on-click-modal="false"
    :close-on-press-escape="false" :before-close="handlePreviewClose">
    <ContentWrap>
      <div id="print-preview-content">
        <!-- 打印预览内容 -->
        <div class="print-header">
          <h3 style="text-align: center; margin-bottom: 20px;">分层审核检查表</h3>
        </div>

        <!-- 基本信息：使用原生 table（避免 el-table 打印问题） -->
        <table id="basic-info-table" border="1" cellspacing="0" cellpadding="8"
          style="width: 100%; border-collapse: collapse; margin-bottom: 20px; font-size: 14px;">
          <tr>
            <td style="width: 10%; text-align: center; font-weight: bold;">等级</td>
            <td style="width: 10%; text-align: center;">{{ allRowData.levelName }}</td>
            <td style="width: 10%; text-align: center; font-weight: bold;">区域</td>
            <td style="width: 10%; text-align: center;">{{ allRowData.areaName }}</td>
            <td style="width: 10%; text-align: center; font-weight: bold;">所属范围</td>
            <td style="width: 10%; text-align: center;">
              <dict-tag :type="DICT_TYPE.BELONG" :value="allRowData.belongType" />
            </td>
            <td style="width: 10%; text-align: center; font-weight: bold;">审核日期</td>
            <td style="width: 15%; text-align: center;">{{ allRowData.auditStartDate }}</td>
            <td style="width: 10%; text-align: center; font-weight: bold;">审核人</td>
            <td style="width: 15%; text-align: center;">{{ allRowData.auditUserName }}</td>
          </tr>
          <tr>
            <td style="text-align: center; font-weight: bold;">状态</td>
            <td style="text-align: center;">
              <dict-tag :type="DICT_TYPE.WRITE_STATUS" :value="allRowData.writeStatus" />
            </td>
            <td style="text-align: center; font-weight: bold;">填报人</td>
            <td style="text-align: center;">{{ allRowData.writeUserName }}</td>
            <td style="text-align: center; font-weight: bold;">填报时间</td>
            <td colspan="6" style="text-align: center;">
              {{ dateFormatter(null, null, allRowData.writeTime) }}
            </td>
          </tr>
        </table>

        <!-- 审核明细 -->
        <el-divider border-style="dashed">审核明细</el-divider>
        <table id="audit-detail-table" border="1" cellspacing="0" cellpadding="8"
          style="width: 100%; border-collapse: collapse; margin-bottom: 20px; font-size: 14px;">
          <thead>
            <tr>
              <th style="width: 100px; text-align: center; font-weight: bold;">分类名称</th>
              <th style="width: 250px; text-align: center; font-weight: bold;">审核项</th>
              <th style="width: 120px; text-align: center; font-weight: bold;">审核结果</th>
              <th style="width: 250px; text-align: center; font-weight: bold;">问题简述</th>
              <th style="width: 150px; text-align: center; font-weight: bold;">责任人</th>
              <th style="width: 150px; text-align: center; font-weight: bold;">计划时间</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(row, index) in formData.detailList" :key="index">
              <td style="text-align: center;">{{ row.auditTypeName }}</td>
              <td style="text-align: center;">{{ row.configName }}</td>
              <td style="text-align: center;">
                {{ getAuditResultLabel(row.auditResult) }}
              </td>
              <td style="text-align: center;">
                {{ row.remark || '--' }}
              </td>
              <td style="text-align: center;">
                {{ row.dutyUserName || '--' }}
              </td>
              <td style="text-align: center;">
                {{ row.planDate || '--' }}
              </td>
            </tr>
            <!-- 可选：如果列表为空，显示无数据 -->
            <tr v-if="!formData.detailList || formData.detailList.length === 0">
              <td colspan="6" style="text-align: center; color: #999;">暂无审核明细数据</td>
            </tr>
          </tbody>
        </table>
      </div>
    </ContentWrap>

    <template #footer>
      <div class="print-actions">
        <el-button type="primary" @click="printPreview">打印</el-button>
        <el-button @click="printPreviewVisible = false">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE, getIntDictOptionsString } from '@/utils/dict'
import { isEmpty } from '@/utils/is'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { AuditPlanAreaApi, AuditPlanArea } from '@/api/business/auditplanarea'
import AuditPlanAreaForm from './AuditPlanAreaForm.vue'
// import AuditPlanAreaForm from './AuditPlanAreaFormPrint.vue'
import jsPDF from 'jspdf'
import html2canvas from 'html2canvas'

/** 审核计划区域 列表 */
defineOptions({ name: 'AuditPlanArea' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<AuditPlanArea[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  levelId: undefined,
  writeStatus: undefined,
  areaName: undefined
})

const formData = ref({
  id: undefined,
  levelId: undefined,
  planId: undefined,
  areaId: undefined,
  auditStartDate: undefined,
  auditEndDate: undefined,
  auditUserId: undefined,
  status: undefined,
  areaName: undefined,
  importantProcesses: undefined,
  recentlyProblem: undefined,
  writeUserId: undefined,
  writeUserName: undefined,
  writeTime: undefined,
  sendUserId: undefined,
  sendUserName: undefined,
  sendTime: undefined,
  auditUserName: undefined,
  writeStatus: undefined,
  levelName: undefined,
  detailList: []
})

const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await AuditPlanAreaApi.getAuditPlanAreaPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}


/** 获取审核结果标签 */
const getAuditResultLabel = (value: string) => {
  const options = getIntDictOptionsString(DICT_TYPE.AUDIT_RESULT)
  const option = options.find(opt => opt.value === value)
  return option ? option.label : value
}

// 打印预览相关
const printPreviewVisible = ref(false)
const printPreviewContent = ref<HTMLElement | null>(null)
const currentTime = computed(() => {
  const now = new Date()
  return `${now.getFullYear()}-${(now.getMonth() + 1).toString().padStart(2, '0')}-${now.getDate().toString().padStart(2, '0')} ${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`
})

const rowOne = ref([])

const rowTwo = ref([])

const rowThree = ref([])

// 存储完整的一行数据，用于打印
const allRowData = ref({})

/** 显示打印预览 */
const showPrintPreview = async (row) => {

  // 2. 清空原有数据
  rowOne.value = []
  rowOne.value.push(row)

  allRowData.value = { ...row }

  formData.value = await AuditPlanAreaApi.getAuditPlanArea(row.id)

  printPreviewVisible.value = true
  // 确保内容渲染完成
  nextTick(() => {
    printPreviewContent.value = document.getElementById('print-preview-content')
  })
}


/** 关闭打印预览 */
const handlePreviewClose = () => {
  printPreviewVisible.value = false
}

/** 打印预览内容 */
const printPreview = () => {
  if (!printPreviewContent.value) return

  // 使用 html2canvas 生成图片
  html2canvas(printPreviewContent.value, {
    scale: 2, // 提高分辨率
    useCORS: true, // 解决跨域问题
    logging: false,
    dpi: 300, // 提高打印质量
    backgroundColor: null
  }).then(canvas => {
    const imgData = canvas.toDataURL('image/png')

    // 创建 PDF
    const pdf = new jsPDF({
      orientation: 'portrait',
      unit: 'mm',
      format: 'a4'
    })

    // 计算 PDF 尺寸
    const imgWidth = 210 // A4宽度(8.27英寸)
    const pageHeight = 297 // A4高度(11.69英寸)
    const imgHeight = canvas.height * imgWidth / canvas.width

    // 添加图片到 PDF
    pdf.addImage(imgData, 'PNG', 0, 0, imgWidth, imgHeight)

    // 保存 PDF 并自动打印
    pdf.save(`审核报告_${currentTime.value}.pdf`)
    pdf.autoPrint()
    pdf.output('dataurlnewwindow')

    // 关闭预览
    printPreviewVisible.value = false
  })
}



const checkedIds = ref<number[]>([])
const handleRowCheckboxChange = (records: AuditPlanArea[]) => {
  checkedIds.value = records.map((item) => item.id);
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await AuditPlanAreaApi.exportAuditPlanArea(queryParams)
    download.excel(data, '审核计划区域.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>


<style scoped>
.print-container {
  position: relative;
}

.print-header {
  text-align: center;
  margin-bottom: 20px;
}

.print-section {
  margin-bottom: 25px;
}

.print-content {
  line-height: 1.6;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  background-color: #fafafa;
  margin-top: 5px;
}

.print-actions {
  text-align: center;
  margin-top: 20px;
}

.print-preview-dialog {
  .el-dialog__body {
    padding: 20px 30px;
  }
}

/* 为打印预览添加打印样式 */
@media print {
  .print-container {
    display: none;
  }

  .print-preview-dialog {
    display: none !important;
  }

  #print-preview-content {
    display: block !important;
  }
}
</style>
